import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map } from 'rxjs/operators';
import { of } from 'rxjs';
import { SearchDrawerService, ShipperBaseService } from '@shared';
import { Router } from '@angular/router';
import { BasicTableComponent } from 'src/app/routes/commom/components/basic-table/basic-table.component';
import { DataService } from '../../../services/data.service';

@Component({
  selector: 'app-datatable-fund-orderSucceed',
  templateUrl: './fund-orderSucceed.component.html',
  styleUrls: ['../../../../commom/less/commom-table.less']
})
export class DatatableFundOrderSucceedComponent extends BasicTableComponent implements OnInit {
  uiView: SFUISchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  isVisibleView = false;
  isVisibleEvaluate = false;
  isVisible = false;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  columns: STColumn[] = [];
  loading: boolean = true;
  resourceStatus: any;
  tabs = {
    receivedQuantity: 0,
    stayQuantity: 0,
    totalCount: 0
  };
  constructor(
    public service: DataService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus == '1') {
      a.regaZj = 1;
    } else if (this.resourceStatus == '2') {
      a.regaZj = '';
    } else {
      a.regaZj = 0;
    }
    const params: any = Object.assign({}, this.sfValue || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
    };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    const a: any = {};
    if (this.resourceStatus == '1') {
      a.regaZj = 1;
    } else if (this.resourceStatus == '2') {
      a.regaZj = '';
    } else {
      a.regaZj = 0;
    }
    const params: any = Object.assign({}, this.sfValue || {});
    delete params._$expand;
    if (this.sfValue) {
      Object.assign(requestOptions.body, {
        ...a,
        ...params
      });
    }
    this.loading = true;
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    this.loading = false;
    return data.map(item => ({
      ...item,
      disabled: item?.billPutStatus
    }));
  };
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  getGoodsSourceStatistical() {
    this.tabs = {
      receivedQuantity: 0,
      stayQuantity: 0,
      totalCount: 0
    };
    const params: any = Object.assign({}, this.reqParams || {});
    delete params.auditStatus;
    this.service.request(this.service.$api_getRegulationZJTabCounts, params).subscribe((res:any) => {
      if (res) {
            this.tabs.receivedQuantity = res.haveReaCount;
            this.tabs.stayQuantity = res.notHaveReaCount;
            this.tabs.totalCount = res.notHaveReaCount + res.haveReaCount;
      }
    });
  }
  selectChange(e: number) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
  //   if(this.sf) {
  // this.sf.setValue('/wayBillCreateTime', {end: "2022-06-16",
  // start: "2022-05-12"});
  //   }
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        waybillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        serialNumberCode: {
          type: 'string',
          title: '流水单号',
          ui: {
            placeholder: '请输入'
          }
        },
        createTime: {
          title: '交易起止时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      {
        title: '监管订单信息(订单上传成功后)',
        children: [
          {
            title: '订单号',
            width: '140px',
            className: 'text-left',
            render: 'billCode'
          },
          {
            title: '运单号',
            width: '140px',
            className: 'text-left',
            index: 'waybillCode'
          },
   
          {
            title: '总金额（运费）',
            width: '100px',
            className: 'text-right',
            render: 'wayAmount'
          },
          {
            title: '支付金额',
            className: 'text-right',
            width: '100px',
            render: 'payAmount'
          },
        ]
      },
      {
        title: '监管资金信息',
        children: [
          {
            title: '上传状态',
            width: '80px',
            className: 'text-center',
            index: 'uploadStatusLabel'
          },
          {
            title: '流水单号',
            width: '100px',
            className: 'text-center',
            index: 'serialNumberCode'
          },
          {
            title: '实际支付金额',
            width: '90px',
            className: 'text-right',
            index: 'realPayAmount'
          },
          {
            title: '支付金额差异',
            width: '90px',
            className: 'text-right',
            index: 'diffAmount'
          },
          {
            title: '银行流水号',
            width: '90px',
            className: 'text-center',
            index: 'bankSerialNumber'
          },
          { title: '交易时间', render: 'createTime', width: '100px', className: 'text-center' },
        ]
      },
      {
        title: '操作',
        fixed: 'right',
        width: '60px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '同步',
            click: _record => this.sign1(_record),
            iif: item => !item?.serialNumberCode,
            acl: { ability: ['superviseOrderSucceed-Synchronization'] }
          }
        ]
      }
    ];
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  tabChange(item: any) {}

  // 同步
  sign1(value?: any) {
    let params: any[] = [];
    if(!value) {
      if (this.selectedRows?.length <= 0) {
        this.service.msgSrv.error('请选择订单！');
        return;
      }
      this.selectedRows.forEach(item => {
        params.push(item?.id);
      });
    } else {
        params.push(value?.id);
    }
    this.service.request(this.service.$api_regulationBillSync, params).subscribe((res: any) => {
      if(res) {
        this.service.msgSrv.success('同步成功！');
        this.st.load()
      }
    })
  }

  // 导出
  exprot() {
    // this.service.exportStart({ ...this.reqParams, pageSize: -1 }, this.service.$api_get_asyncExportExamineBillList);
  }
}
